<?php
/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2013-8-20
 * @package TinPhp
 */

class TinSession
{
  /**
   * start/resume a session 
   *
   * session id is stored in cookie (identified by key 'PHPSESSID')
   */
  public static function start()
  {
    $result =session_start();
    return  $result;
  }

  /**
   * destroy the current session
   */
  public static function destroy()
  {
    return session_destroy();
  }

  /**
   * return TRUE if session is started/resumed
   * otherwise return FALSE
   */
  public static function started()
  {
    $sessid = TinSession::id();
    return !empty($sessid);
  }

  /**
   * get session id
   */
  public static function id()
  {
    return session_id();
  }

  /**
   * set session id
   */
  public static function setId($id)
  {
    session_id($id);
  }

  /**
   * set session entry
   *
   * @param string $key the name indicates the entry
   * @param string $value the value of the entry
   *
   * @return TRUE if session successfully set, otherwise return FALSE
   */
  public static function set($key, $value)
  {
    if (!$key || !$value) {
      return FALSE;
    }

    $value = @serialize($value);

    $_SESSION[$key] = $value;
    return TRUE;
  }

  /**
   * remove entry/entries indicates by @keys
   *
   * return TRUE if every entry/entries is successfully removed from session
   */
  public static function remove($keys)
  {
    if (!$keys) {
      return FALSE;
    }

    $keyarr = array();
    if (!is_array($keys)) {
      if (!is_string($keys)) {
        return FALSE;
      } else {
        $keyarr[] = $keys;
      }
    } else {
      $keyarr = $keys;
    }
 
    foreach ($keyarr as $key) {
      if (!TinSession::exists($key)) {
        return FALSE;
      }
 
      unset($_SESSION[$key]);
    }

    return TRUE;
  }

  /**
   * get value of the entry identified by @key from session
   *
   * @return NULL if the entry is not exist
   */
  public static function get($key)
	{
     TinSession::start();

		if (!TinSession::exists($key)) {
			return NULL;
		}

    $value = $_SESSION[$key];
    if (!$value) {
      return NULL;
    } else {
      $unse = @unserialize($value);
      return ($unse) ? $unse : NULL;
    } 
	}

  /**
   * check the entry identified by @key is exist
   */
  public static function exists($key)
  {
    return isset($_SESSION[$key]);
  }
}
?>